package com.ant.common.exceptions;

import com.ant.common.constant.RequestConstant;
import com.ant.common.result.ResponseResult;
import com.ant.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * springmvc异常处理
 * 全局异常拦截
 */
@RestControllerAdvice
public class ExcepHandlerAdvice {

    @Autowired
    private MessageSource messageSource;

    private static final Logger log = LoggerFactory.getLogger("ExceptionHandlerAdvice");

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult badRequestException(IllegalArgumentException exception) {
        log.error(" 400 Bad Request ", exception);
        return new ResponseResult(false, "系统异常", HttpStatus.BAD_REQUEST.value(), null, 0, RequestConstant.WRAPPED_RESULT_TYPE.SYSTEM.getName());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult exception(Throwable throwable) {
        log.error(" 500 Internal Server Error", throwable);
        return new ResponseResult(false, "系统异常", HttpStatus.INTERNAL_SERVER_ERROR.value(), null, 0, RequestConstant.WRAPPED_RESULT_TYPE.SYSTEM.getName());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseResult exception(NativeWebRequest request, BusinessException e) {
        ResponseResult vr = new ResponseResult();
        vr.setCode(Integer.parseInt(e.getCode()));
        vr.setMsg(StringUtil.isNotEmpty(e.getMessage()) ? e.getMessage() : "系统异常");
        log.error("Business Error", e);
        return vr;
    }
}
